package com.aha.secondchapter.fourth;

/**
 * 链表
 * Created by wangxin on 2015/11/1.
 */
public class MyLinkedList {
    private Node first;
    private Node last;
    private int size;

    public static void main(String[] args) {
        MyLinkedList m = new MyLinkedList();
        m.add(1);
        m.add(2);
        m.add(1,3);
        System.out.println(m.getNode(1).data);
        Node n = m.getFirstNode();
        while(n!=null){
            System.out.println(n.data);
            n = n.next;
        }

    }
    public MyLinkedList(){

    }
    public Node getFirstNode(){
        return getNode(0);
    }
    public Node getNode(int index){
        if(index>size) throw new IndexOutOfBoundsException();
        Node n = first;
        for (int i = 0; i < index; i++) {
            n=n.next;
        }
        return n;
    }
    public void add(int addr, int data){
        Node n = getNode(addr);
        Node newNode = new Node(data,null,null);
        newNode.next = n;
        if(n.pre != null){
            n.pre.next = newNode;
            newNode.pre = n.pre;
        }
        n.pre = newNode;
        if(addr==0) first = newNode;
    }
    public void add(int i){
        Node l = last;
        Node n = new Node(i,l,null);
        last = n;
        if(l == null){
            first = n;
        }else{
            l.next = n;
        }
        size++;
    }
    public int get(int index){
        if(index>size) throw new IndexOutOfBoundsException();
        Node n = first;
        for (int i = 0; i < index; i++) {
            n=n.next;
        }
        return n.data;
    }
    private static class Node{
        public int data;
        public Node next;
        public Node pre;
        Node(int data, Node pre, Node next){
            this.data = data;
            this.pre = pre;
            this.next = next;
        }
    }
}

